package com.example.common.util;

import lombok.experimental.UtilityClass;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author pywang
 * @Description
 * @date 2020-04-20 17:13
 **/
@UtilityClass
public class ObjUtil {

    public <T> T map (Object source, Class<T> target, Map<String, String> propertyMap){
        Map<String, String> targetPropertyMap = null;
        T t = null;
        try {
            t = target.newInstance();
            targetPropertyMap = BeanUtils.describe(t);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CollectionUtils.isEmpty(targetPropertyMap)) {
            return t;
        }
        final Map<String, String> targetMap = targetPropertyMap;
        final T result = t;
        propertyMap.forEach((k, v)->{
            try {
                if (targetMap.containsKey(k)){
                    BeanUtils.setProperty(result, v, BeanUtils.getProperty(source, k));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return result;
    }
}
